package org.example.reactive.demo1.api;

import lombok.RequiredArgsConstructor;
import org.example.reactive.demo1.entity.QQNickname;
import org.example.reactive.demo1.exception.BaseException;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;


/**
 * @author Gong.Yang
 * 非阻塞网络IO
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/web_client")
public class WebClientTestApi {

    WebClient qqClient = WebClient.create("https://api.oioweb.cn/api/qq/");

    @GetMapping("/{qqNumber}")
    public Mono<QQNickname> findByQQ(@PathVariable String qqNumber) {
        String uri = UriComponentsBuilder.fromUriString("nickname")
                .queryParam("qq", qqNumber)
                .toUriString();
        return qqClient.get()
                .uri(uri)
                .retrieve()
                //转换成业务异常
                .onStatus(HttpStatusCode::isError, x -> Mono.just(new BaseException("变成！业务异常吧！")))
                .bodyToMono(QQNickname.class)
                .handle((qqNickname, sink) -> {
                    if (!qqNickname.getCode().equals(200)) {
                        sink.error(new BaseException("这里也抛出一个业务异常"));//最近qq这个接口关了 返回的code都是400
                        return;
                    }
                    sink.next(qqNickname);
                });
    }
}
